<template>
  <div class="user-management">
    <TopNavigation :showTaskRoleSection="false" />
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <div class="card">
      <div class="toolbar">
        <div class="search-container">
          <div class="input-group">
            <input type="text" class="input" placeholder="搜索用户姓名或认证号" v-model="searchKeyword" @input="searchUsers" />
            <button class="btn btn-primary" @click="searchUsers">
              搜索
            </button>
          </div>
        </div>
        <button class="btn btn-primary" @click="showAddModal">新建用户</button>
      </div>

      <div class="table-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>

        <!-- 用户卡片网格 -->
        <div v-else class="users-grid">
          <div v-for="user in paginatedUsers" :key="user.userId" class="user-card">
            <div class="user-header">
              <div class="user-info">
                <h3 class="user-name">{{ user.userName }}</h3>
                <p class="user-auth-id">{{ user.authId }}</p>
              </div>
              <div class="user-type-badge">{{ user.userType }}</div>
            </div>
            <div class="user-content">
              <div class="user-detail">
                <span class="detail-label">邮箱:</span>
                <span class="detail-value">{{ user.email }}</span>
              </div>
              <div class="user-detail">
                <span class="detail-label">所属部门:</span>
                <span class="detail-value">{{ user.deptName }}</span>
              </div>
            </div>
            <div class="user-actions">
              <button class="btn btn-edit" @click="showEditModal(user)" title="修改用户">
                ✏️
              </button>
              <button class="btn btn-password" @click="showChangePasswordModal(user)" title="修改密码">
                🔑
              </button>
              <button class="btn btn-delete" @click="deleteUser(user.userId)" title="删除用户">
                🗑️
              </button>
            </div>
          </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <button class="btn btn-default" @click="onPageChange(Math.max(1, page - 1))" :disabled="page <= 1 || totalItems === 0">
            上一页
          </button>
          <span class="page-info">
            第 {{ page }} 页 / 共 {{ totalPages }} 页 (总计 {{ totalItems }} 条)
          </span>
          <button class="btn btn-default" @click="onPageChange(Math.min(totalPages, page + 1))"
            :disabled="page >= totalPages || totalItems === 0">
            下一页
          </button>
          <div class="page-size-selector">
            <span>每页显示:</span>
            <select class="select" v-model="pageSize" @change="onPageSizeChange">
              <option :value="5">5条</option>
              <option :value="10">10条</option>
              <option :value="20">20条</option>
              <option :value="50">50条</option>
            </select>
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-if="!loading && users.length === 0" class="empty-state">
          <div class="empty-icon">👥</div>
          <div class="empty-text">暂无用户数据</div>
          <div class="empty-hint">点击上方按钮添加用户</div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑用户模态框 -->
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">{{ isEditMode ? '编辑用户' : '新建用户' }}</h3>
          <button class="btn btn-default" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <!-- 错误信息显示区域 -->
          <div v-if="showError" class="error-message">
            <div class="error-icon">⚠️</div>
            <div class="error-text">{{ errorMessage }}</div>
          </div>

          <div class="form-item">
            <label class="form-label">认证号</label>
            <input type="text" class="input" v-model="formData.authId" placeholder="请输入认证号" :disabled="isEditMode" />
          </div>
          <div class="form-item">
            <label class="form-label">中文姓名</label>
            <input type="text" class="input" v-model="formData.userName" placeholder="请输入中文姓名" />
          </div>
          <div class="form-item">
            <label class="form-label">邮箱</label>
            <input type="email" class="input" v-model="formData.email" placeholder="请输入邮箱" />
          </div>
          <div class="form-item">
            <label class="form-label">所属部门</label>
            <select class="select" v-model="formData.deptId" @change="onDeptChange">
              <option value="">请选择部门</option>
              <option v-for="dept in departments" :key="dept.id" :value="dept.id">{{ dept.name }}</option>
            </select>
          </div>
          <div class="form-item">
            <label class="form-label">用户类型</label>
            <select class="select" v-model="formData.userType">
              <option value="管理员">管理员</option>
              <option value="架构">架构</option>
              <option value="开发">开发</option>
              <option value="测试">测试</option>
              <option value="运维">运维</option>
              <option value="其他">其他</option>
            </select>
          </div>
          <div v-if="!isEditMode" class="form-item">
            <label class="form-label">密码</label>
            <input type="password" class="input" v-model="formData.password" placeholder="请输入密码" />
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="closeModal">取消</button>
          <button class="btn btn-primary" @click="saveUser">{{ isEditMode ? '更新' : '确定' }}</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 修改密码模态框 -->
  <div v-if="showPasswordModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">修改密码</h3>
        <button class="btn btn-default" @click="closePasswordModal">×</button>
      </div>
      <div class="modal-body">
        <!-- 错误信息显示区域 -->
        <div v-if="showPasswordError" class="error-message">
          <div class="error-icon">⚠️</div>
          <div class="error-text">{{ passwordErrorMessage }}</div>
        </div>

        <div class="form-item">
          <label class="form-label">用户</label>
          <input type="text" class="input" :value="passwordFormData.userName" disabled />
        </div>
        <div class="form-item">
          <label class="form-label">旧密码</label>
          <input type="password" class="input" v-model="passwordFormData.oldPassword" placeholder="请输入旧密码" />
        </div>
        <div class="form-item">
          <label class="form-label">新密码</label>
          <input type="password" class="input" v-model="passwordFormData.newPassword" placeholder="请输入新密码" />
        </div>
        <div class="form-item">
          <label class="form-label">确认新密码</label>
          <input type="password" class="input" v-model="passwordFormData.confirmPassword" placeholder="请再次输入新密码" />
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="closePasswordModal">取消</button>
        <button class="btn btn-primary" @click="changePassword">确定</button>
      </div>
    </div>
  </div>

  <!-- 删除确认弹窗 -->
  <div v-if="showDeleteModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">确认删除</h3>
        <button class="btn btn-default" @click="closeDeleteModal">×</button>
      </div>
      <div class="modal-body">
        <div class="delete-warning">
          <div class="warning-icon">⚠️</div>
          <div class="warning-text">
            <p>您确定要删除用户 <strong>{{ deleteUserData.userName }}</strong> 吗？</p>
            <p class="warning-note">此操作不可撤销，请谨慎操作。</p>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="closeDeleteModal">取消</button>
        <button class="btn btn-danger" @click="confirmDelete" :disabled="deleteLoading">
          {{ deleteLoading ? '删除中...' : '确认删除' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import TopNavigation from '../components/TopNavigation.vue'
import { ref, computed, onMounted } from 'vue'
import { userService } from '../services/userService.js'
import { departmentService } from '../services/departmentService.js'

// 分页相关变量
const page = ref(1)
const pageSize = ref(10)
const totalItems = ref(0) // 服务器端总数据量

// 排序相关变量
const sortField = ref('')
const sortOrder = ref('asc') // 'asc' 或 'desc'

// 处理分页大小变化
const onPageSizeChange = () => {
  // 重置到第一页并重新获取数据
  page.value = 1;
  fetchUsers();
}

// 处理页码变化
const onPageChange = (newPage) => {
  // 确保页码在有效范围内
  const validPage = Math.max(1, Math.min(newPage, totalPages.value));
  page.value = validPage;
  fetchUsers();
}

// 初始化数据
const departments = ref([])
const users = ref([])
const loading = ref(true)
const error = ref(null)

// 用户类型列表，用于确保输入值的有效性
const validUserTypes = ['管理员', '架构', '开发', '测试', '运维', '其他']

// 从API获取部门数据
const fetchDepartments = async () => {
  try {
    console.log('开始获取部门数据...')
    const response = await departmentService.getDepartments()
    console.log('部门数据响应:', response)

    if (response.code === 200) {
      // 确保部门数据格式正确，处理可能的字段差异
      departments.value = (response.data || []).map(dept => ({
        id: dept.id || dept.deptId,
        name: dept.name || dept.deptName
      })).filter(dept => dept.id && dept.name) // 过滤无效数据
      console.log('处理后的部门数据:', departments.value)
    } else {
      throw new Error(response.message || '获取部门数据失败')
    }
  } catch (err) {
    error.value = err.message || '获取部门数据时发生错误'
    console.error('Failed to fetch departments:', err)
    showMessage(error.value, 'error')
  }
}

// 从API获取用户数据
const fetchUsers = async () => {
  try {
    loading.value = true
    const params = {
      page: page.value - 1, // 转换为0-based索引
      size: pageSize.value
    }
    // 如果有搜索关键词，添加到参数中
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim()
    }

    const response = await userService.getUsers(params)
    if (response.code === 200) {
      // 根据实际返回格式解析数据
      if (Array.isArray(response.data)) {
        // 数据直接在data字段中，总数在extra.total中
        users.value = response.data
        totalItems.value = response.extra?.total || response.data.length
      } else if (response.data && typeof response.data === 'object') {
        // 数据在data的子字段中
        users.value = response.data.content || response.data.list || []
        totalItems.value = response.data.totalElements || response.data.total || 0
      } else {
        users.value = response.data || []
        totalItems.value = users.value.length
      }
    } else {
      throw new Error(response.message || '获取用户数据失败')
    }
  } catch (err) {
    error.value = err.message || '获取用户数据时发生错误'
    console.error('Failed to fetch users:', err)
    showMessage(error.value, 'error')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  // 优先加载部门数据
  await fetchDepartments()
  // 部门数据加载完成后再加载用户数据
  fetchUsers()
})

// 搜索关键词
const searchKeyword = ref('')

// 模态框相关状态
const showModal = ref(false)
const isEditMode = ref(false)
const currentUserId = ref(null)
const formData = ref({
  authId: '',
  userName: '',
  email: '',
  deptId: '',
  deptName: '',
  userType: '',
  password: ''
})

// 弹窗内错误信息状态
const errorMessage = ref('')
const showError = ref(false)

// 修改密码模态框相关状态
const showPasswordModal = ref(false)
const passwordFormData = ref({
  userId: '',
  userName: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordErrorMessage = ref('')
const showPasswordError = ref(false)

// 删除确认弹窗相关状态
const showDeleteModal = ref(false)
const deleteUserData = ref({
  userId: '',
  userName: ''
})
const deleteLoading = ref(false)

// 排序函数
const sort = (field) => {
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = field
    sortOrder.value = 'asc'
  }
}

// 计算总页数
const totalPages = computed(() => {
  if (!pageSize.value || pageSize.value <= 0) return 1;
  return Math.ceil(totalItems.value / pageSize.value) || 1;
})

// 直接使用从服务器获取的用户数据，不需要前端分页
const paginatedUsers = computed(() => users.value)

// 搜索用户
const searchUsers = () => {
  // 重置到第一页并重新获取数据
  page.value = 1;
  fetchUsers();
}

// 部门选择变化处理
const onDeptChange = () => {
  if (formData.value.deptId) {
    const selectedDept = departments.value.find(dept => dept.id === formData.value.deptId)
    formData.value.deptName = selectedDept ? selectedDept.name : ''
  } else {
    formData.value.deptName = ''
  }
}

// 显示新增模态框
const showAddModal = () => {
  isEditMode.value = false
  formData.value = {
    authId: '',
    userName: '',
    email: '',
    deptId: '',
    deptName: '',
    userType: '',
    password: ''
  }
  showModal.value = true
}

// 显示编辑模态框
const showEditModal = (user) => {
  isEditMode.value = true
  currentUserId.value = user.userId
  formData.value = {
    authId: user.authId,
    userName: user.userName,
    email: user.email,
    deptId: user.deptId || '',
    deptName: user.deptName,
    // 直接使用中文值
    userType: user.userType,
    password: '' // 编辑时不显示密码
  }
  showModal.value = true
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
  errorMessage.value = ''
  showError.value = false
}

// 保存用户
const saveUser = async () => {
  // 清除之前的错误信息
  errorMessage.value = ''
  showError.value = false

  // 表单验证
  if (!formData.value.authId.trim()) {
    errorMessage.value = '请输入认证号'
    showError.value = true
    return
  }
  if (!formData.value.userName.trim()) {
    errorMessage.value = '请输入中文姓名'
    showError.value = true
    return
  }
  if (!formData.value.email.trim()) {
    errorMessage.value = '请输入邮箱'
    showError.value = true
    return
  }
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(formData.value.email)) {
    errorMessage.value = '请输入有效的邮箱地址'
    showError.value = true
    return
  }
  if (!formData.value.deptId) {
    errorMessage.value = '请选择所属部门'
    showError.value = true
    return
  }

  // 验证用户类型
  if (!validUserTypes.includes(formData.value.userType)) {
    errorMessage.value = '请选择有效的用户类型'
    showError.value = true
    return
  }

  // 新增用户时验证密码
  if (!isEditMode.value && !formData.value.password.trim()) {
    errorMessage.value = '请输入密码'
    showError.value = true
    return
  }

  // 密码长度验证
  if (!isEditMode.value && formData.value.password.length < 6) {
    errorMessage.value = '密码长度不能少于6位'
    showError.value = true
    return
  }

  try {
    console.log('开始保存用户...')
    if (isEditMode.value) {
      // 更新用户
      console.log('更新用户ID:', currentUserId.value)
      console.log('更新数据:', {
        authId: formData.value.authId,
        userName: formData.value.userName,
        email: formData.value.email,
        deptId: formData.value.deptId,
        deptName: formData.value.deptName,
        userType: formData.value.userType
      })
      const response = await userService.updateUser(currentUserId.value, {
        authId: formData.value.authId,
        userName: formData.value.userName,
        email: formData.value.email,
        deptId: formData.value.deptId,
        deptName: formData.value.deptName,
        userType: formData.value.userType
      })
      console.log('更新用户响应:', response)
      if (response.code === 200) {
        // 先重新获取用户列表，确保数据同步
        await fetchUsers()
        console.log('用户列表已从服务器刷新')
        showMessage('用户更新成功', 'success')
        closeModal()
      } else {
        throw new Error(response.message || '更新用户失败')
      }
    } else {
      // 新增用户
      const response = await userService.createUser({
        authId: formData.value.authId,
        userName: formData.value.userName,
        email: formData.value.email,
        deptId: formData.value.deptId,
        deptName: formData.value.deptName,
        userType: formData.value.userType,
        password: formData.value.password
      })
      if (response.code === 201) {
        // 重新获取用户列表，确保数据同步
        await fetchUsers()
        console.log('用户列表已从服务器刷新')
        showMessage('用户创建成功', 'success')
        console.log('准备关闭弹窗，当前showModal值:', showModal.value)
        closeModal()
        console.log('closeModal调用完成，当前showModal值:', showModal.value)
      } else {
        throw new Error(response.message || '创建用户失败')
      }
    }
  } catch (err) {
    console.error('Failed to save user:', err)

    // 处理HTTP错误响应
    if (err.response && err.response.data && err.response.data.message) {
      errorMessage.value = err.response.data.message
    } else if (err.message) {
      errorMessage.value = err.message
    } else {
      errorMessage.value = '操作失败，请检查网络连接或联系管理员'
    }

    showError.value = true
  }
}

// 显示删除确认弹窗
const deleteUser = (id) => {
  const user = users.value.find(u => u.userId === id)
  if (user) {
    deleteUserData.value = {
      userId: id,
      userName: user.userName
    }
    showDeleteModal.value = true
  }
}

// 关闭删除确认弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
  deleteUserData.value = {
    userId: '',
    userName: ''
  }
  deleteLoading.value = false
}

// 确认删除用户
const confirmDelete = async () => {
  try {
    deleteLoading.value = true
    const response = await userService.deleteUser(deleteUserData.value.userId)
    if (response.code === 200) {
      // 重新获取用户列表，确保数据同步
      await fetchUsers()
      // 处理分页问题，如果当前页没有数据且不是第一页，则跳转到上一页
      if (users.value.length === 0 && page.value > 1) {
        page.value -= 1
        await fetchUsers()
      }
      showMessage('用户删除成功', 'success')
      closeDeleteModal()
    } else {
      throw new Error(response.message || '删除用户失败')
    }
  } catch (err) {
    console.error('Failed to delete user:', err)

    // 处理HTTP错误响应
    let errorMsg = '删除失败'
    if (err.response && err.response.data && err.response.data.message) {
      errorMsg = err.response.data.message
    } else if (err.message) {
      errorMsg = err.message
    }

    showMessage(errorMsg, 'error')
  } finally {
    deleteLoading.value = false
  }
}

// 显示修改密码模态框
const showChangePasswordModal = (user) => {
  passwordFormData.value = {
    userId: user.userId,
    userName: user.userName,
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordErrorMessage.value = ''
  showPasswordError.value = false
  showPasswordModal.value = true
}

// 关闭修改密码模态框
const closePasswordModal = () => {
  showPasswordModal.value = false
  passwordErrorMessage.value = ''
  showPasswordError.value = false
}

// 修改密码
const changePassword = async () => {
  // 清除之前的错误信息
  passwordErrorMessage.value = ''
  showPasswordError.value = false

  // 表单验证
  if (!passwordFormData.value.oldPassword.trim()) {
    passwordErrorMessage.value = '请输入旧密码'
    showPasswordError.value = true
    return
  }
  if (!passwordFormData.value.newPassword.trim()) {
    passwordErrorMessage.value = '请输入新密码'
    showPasswordError.value = true
    return
  }
  if (passwordFormData.value.newPassword.length < 6) {
    passwordErrorMessage.value = '新密码长度不能少于6位'
    showPasswordError.value = true
    return
  }
  if (!passwordFormData.value.confirmPassword.trim()) {
    passwordErrorMessage.value = '请确认新密码'
    showPasswordError.value = true
    return
  }
  if (passwordFormData.value.newPassword !== passwordFormData.value.confirmPassword) {
    passwordErrorMessage.value = '两次输入的新密码不一致'
    showPasswordError.value = true
    return
  }

  try {
    // 调用修改密码API
    const response = await userService.changePassword({
      userId: passwordFormData.value.userId,
      oldPassword: passwordFormData.value.oldPassword,
      newPassword: passwordFormData.value.newPassword
    })

    if (response.code === 200) {
      showMessage('密码修改成功', 'success')
      closePasswordModal()
    } else {
      throw new Error(response.message || '修改密码失败')
    }
  } catch (err) {
    console.error('Failed to change password:', err)

    // 处理HTTP错误响应
    if (err.response && err.response.data && err.response.data.message) {
      passwordErrorMessage.value = err.response.data.message
    } else if (err.message) {
      passwordErrorMessage.value = err.message
    } else {
      passwordErrorMessage.value = '修改密码失败，请检查网络连接或联系管理员'
    }

    showPasswordError.value = true
  }
}

// 消息提示函数
const showMessage = (message, type = 'info') => {
  // 创建消息元素
  const msgElement = document.createElement('div')
  msgElement.className = `message message-${type}`
  msgElement.textContent = message

  // 添加到body
  document.body.appendChild(msgElement)

  // 3秒后移除
  setTimeout(() => {
    msgElement.style.opacity = '0'
    setTimeout(() => {
      document.body.removeChild(msgElement)
    }, 300)
  }, 3000)
}
</script>

<style scoped>
.user-management {
  width: 100%;
}

.page-header {
  margin-bottom: var(--spacing-xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.page-header h2 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

/* 继承全局样式 */
.card {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-base);
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: var(--shadow-md);
}

/* 用户卡片网格布局 */
.users-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 24px;
  padding: 24px;
}

/* 用户卡片样式 */
.user-card {
  background: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  padding: 24px;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.user-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
  border-color: var(--primary-color);
}

/* 用户卡片头部 */
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px 0;
  line-height: 1.4;
}

.user-auth-id {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin: 0;
  font-family: 'Courier New', monospace;
  background: var(--bg-light);
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.user-type-badge {
  background: var(--primary-color);
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: var(--font-size-xs);
  font-weight: 500;
  white-space: nowrap;
}

/* 用户卡片内容 */
.user-content {
  flex: 1;
  margin-bottom: 16px;
}

.user-detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px 0;
  border-bottom: 1px solid var(--border-light);
}

.user-detail:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.detail-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  font-weight: 500;
  min-width: 80px;
}

.detail-value {
  font-size: var(--font-size-sm);
  color: var(--text-primary);
  text-align: right;
  word-break: break-all;
}

/* 用户操作按钮 */
.user-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: auto;
}

.user-actions .btn {
  padding: 8px 12px;
  border: none;
  border-radius: var(--border-radius-sm);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
  min-width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-edit {
  background: var(--success-color);
  color: white;
}

.btn-edit:hover {
  background: var(--success-hover);
  transform: scale(1.05);
}

.btn-password {
  background: var(--warning-color);
  color: white;
}

.btn-password:hover {
  background: var(--warning-hover);
  transform: scale(1.05);
}

.btn-delete {
  background: var(--danger-color);
  color: white;
}

.btn-delete:hover {
  background: var(--danger-hover);
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .users-grid {
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 20px;
    padding: 20px;
  }
  
  .user-card {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .users-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
    padding: 16px;
  }
  
  .user-card {
    padding: 16px;
    min-height: 180px;
  }
  
  .user-name {
    font-size: var(--font-size-md);
  }
  
  .user-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .user-type-badge {
    align-self: flex-start;
  }
}

@media (max-width: 480px) {
  .users-grid {
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 12px;
  }
  
  .user-card {
    padding: 16px;
  }
  
  .user-name {
    font-size: var(--font-size-md);
  }
  
  .user-actions .btn {
    padding: 6px 10px;
    font-size: 12px;
    min-width: 32px;
    height: 32px;
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

.search-container {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
  flex: 1;
  min-width: 280px;
}

.table-container {
  overflow-x: auto;
}

.table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--font-size-base);
}

.table th,
.table td {
  padding: 12px var(--spacing-lg);
  text-align: left;
  border-bottom: 1px solid var(--border-base);
}

.table th {
  font-weight: 500;
  color: var(--text-regular);
  background-color: var(--bg-light);
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
}

.table tr:hover {
  background-color: var(--bg-hover);
}

.table tr:last-child td {
  border-bottom: none;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: var(--text-secondary);
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-md);
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 16px;
  border: 2px dashed #cbd5e1;
  margin: 20px 0;
  transition: all 0.3s ease;
}

.empty-state:hover {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-color: #94a3b8;
}

.empty-icon {
  font-size: 64px;
  opacity: 0.6;
  margin-bottom: var(--spacing-sm);
  transition: all 0.3s ease;
}

.empty-state:hover .empty-icon {
  transform: scale(1.1);
  opacity: 0.8;
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  color: #475569;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
  color: #64748b;
  font-style: italic;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-md);
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.form-item {
  margin-bottom: var(--spacing-lg);
  transition: all 0.3s ease;
}

.form-item:focus-within {
  transform: translateX(5px);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-sm);
  font-weight: 500;
  color: var(--text-regular);
}

/* 按钮样式增强 */
.btn {
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
}

.btn:hover {
  transform: translateY(-1px);
}

.btn:active {
  transform: translateY(0);
}

/* 模态框动画增强 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(2px);
}

.modal-content {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-lg);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: var(--font-size-lg);
  font-weight: 500;
  color: var(--text-primary);
  margin: 0;
}

.modal-body {
  padding: var(--spacing-lg);
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-base);
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  flex-wrap: wrap;
}

/* 消息提示样式增强 */
.message {
  position: fixed;
  top: 80px;
  right: var(--spacing-xl);
  padding: var(--spacing-md) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  color: #ffffff;
  font-size: var(--font-size-base);
  font-weight: 500;
  box-shadow: var(--shadow-lg);
  z-index: 1000;
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-sm);
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.message-success {
  background-color: var(--success-color);
}

.message-error {
  background-color: var(--error-color);
}

/* 弹窗内错误信息样式 */
.error-message {
  background-color: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: var(--border-radius-md);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-sm);
  animation: errorFadeIn 0.3s ease;
}

.error-icon {
  font-size: 18px;
  flex-shrink: 0;
}

.error-text {
  color: #dc2626;
  font-size: var(--font-size-sm);
  line-height: 1.5;
  word-break: break-word;
}

@keyframes errorFadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-container {
    width: 100%;
  }

  .table th,
  .table td {
    padding: 8px var(--spacing-md);
    font-size: var(--font-size-sm);
  }

  .modal-content {
    width: 95%;
    margin: 20px;
  }

  .message {
    right: var(--spacing-md);
    left: var(--spacing-md);
  }
}

/* 删除确认弹窗样式 */
.delete-warning {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-md);
  padding: var(--spacing-lg);
  background-color: #fef3cd;
  border: 1px solid #ffeaa7;
  border-radius: var(--border-radius-md);
  margin-bottom: var(--spacing-lg);
}

.warning-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.warning-text {
  flex: 1;
}

.warning-text p {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-color);
}

.warning-text p:last-child {
  margin-bottom: 0;
}

.warning-note {
  font-size: var(--font-size-sm);
  color: #856404;
  font-style: italic;
}

.warning-text strong {
  color: var(--primary-color);
  font-weight: 600;
}

.btn-danger:disabled {
  background-color: #dc3545;
  opacity: 0.6;
  cursor: not-allowed;
}

/* 排序相关样式 */
.sortable {
  cursor: pointer;
  user-select: none;
  position: relative;
  transition: background-color 0.2s ease;
}

.sortable:hover {
  background-color: var(--bg-hover);
}

.sort-icon {
  margin-left: var(--spacing-xs);
  font-size: 12px;
  color: var(--primary-color);
}

/* 操作按钮间距 */
.action-buttons {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
}

.action-buttons .btn {
  white-space: nowrap;
}
</style>